from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp

from base_page import BaseHandler
from data import Request
from data import Message

class ViewRequestHandler(BaseHandler):
  def ProcessGet(self):
    self.Setup('view_request.html', show_search_box=True)
    # get request
    req = self.GetEntityByKeyName('qid')
    if req == None:
      self.RedirectAndRaise('/')
    self.template_values['req'] = req
    self.template_values['creator'] = req.creator
    # get pledges
    self.template_values['pledges'] = list(req.pledge_set)
    # get orders
    self.template_values['orders'] = list(req.order_set)
    # get messages
    query = db.GqlQuery("SELECT * FROM Message WHERE key_str = '%s'" % req.key())
    self.template_values['req_messages'] = list(query)

    self.Render()

  def ProcessPost(self):
    self.Setup('view_request.html', show_search_box=True)
    if self.post_action == 'Action.subscribe':
      self.HandleSubscribe()
    else:
      self.JsonErrorReturn('Unknown action')

  def HandleSubscribe(self):
    req = self.GetEntityOrShowError('qid')
    is_subscribe = self.request.get('is_subscribe')
    if is_subscribe == '1':
      # TODO: check if already exists
      req.notifiers.append('huangstc@gmail.com')
    elif is_subscribe == '0':
      #TODO: remove
      req.notifiers = []

    req.put()
    self.RedirectAndRaise('/viewrequest?qid=%s' % req.key())
    # check if the email is already in the notify list

